$(function () {

	loadGridTable2();

	var beCheckedPromot = $("input[name=promot]:checked").val();
	if (beCheckedPromot != "custom") {
    	$("#promot_grid").hide();
  	} // 隐藏自定义选择用的grid
  	if (beCheckedPromot != "someCategory") {
    	$("#seller_cats_promote_div").hide();
  	}
  	
	$('#item_key_2').keypress(function(event) {
	    if ((event.keyCode == 13)) {// 在这里接收的是Enter事件,S的ASCII码为13。
			doSearch2();
	    }
	});
    
  	$("#seller_cats_2").change(function () {
   		doSearch2();
  	});
  
  	$("#approve_status_2").change(function () {
    	doSearch2();
  	});
  	
  	$(".install_place_div").click(function() {
		var ckb_id = $(this).attr("type");
		var st = $("#"+ckb_id).attr("checked");
		$("#"+ckb_id).attr("checked", !st);
	});
});

function loadGridTable2() {
  $("#promot_gridTable").jqGrid({
    url: "items.action?approveStatus="+$("#approve_status_2").val(),
    datatype: "json",
    height: 520,
    width: 500,
    colNames: ["编号", "图片", "名称", "价格", "pic_url", "frank_title"],
    colModel: [{
      name: "iid",
      index: "iid",
      hidden: true
    },
    {
      name: "pic_url",
      index: "pic_url",
      formatter:formatItemPic,
      width: "60",
      align:"center",
      sortable: false
    },
    {
      name: "title",
      index: "title",
      formatter:formateadorLink,
      width: "350"
    },
    {
      name: "price",
      index: "price",
      align:"center",
      sorttype: "int",
      width: "80"
    },
    {
      name: "pic_url",
      index: "pic_url",
      hidden: true
    },
    {
      name: "frank_title",
      index: "frank_title",
      hidden: true
    }],
    sortname: "delist_time",
    sortorder: "desc",
    viewrecords: true,
    rowNum: 8,
    rowList: [8, 15, 25],
    multiselect: true,
    multiselectWidth: 50,
    loadComplete: function () {
		setPromotGridTableSelection();
      	setImageCellHeight('promot_gridTable');
    },
    onSelectRow: function (rowid, status) {
      	if (rowid === null) {
        	return;
      	}
      	var ret = $("#promot_gridTable").jqGrid("getRowData", rowid);
      	var iid = "piid" + ret.iid;
      	var oldsrc = $("#" + iid + " img").attr("src");
      	if (status) {
        	if (oldsrc!==undefined && oldsrc!==null) return;
        	
        	var title_html = buildSimpleTitle(ret);
        	var onClickButtonHtml ="<input type='button' class='btn2 pbtn_60' onmouseout=\"this.style.borderColor='#dcdcdc'\" onmouseover=\"this.style.borderColor='#f76b00'\" value='删除' style=\"border-color: rgb(220, 220, 220);\"  onclick=\"onClickDelete_Step2('" + iid + "')\">"
        	var result = "<div id='" + iid + "' class='piids_promot'><img src='" + ret.pic_url + "'><br/>" + onClickButtonHtml + "</div>";
        	$("#promot_resp").append(result);
      	} else {
			$("#" + iid).remove();
      	}
    },
    onSelectAll: function (ids, status) {
		if (ids===undefined||ids===null||ids.length===0) return;

		if(status){
        	for (i = 0; i < ids.length; i++) {
          		var ret = $("#promot_gridTable").jqGrid("getRowData", ids[i]);
          		var iid = "piid" + ret.iid;
          		var oldsrc = $("#" + iid + " img").attr("src");
          		if (oldsrc===undefined || oldsrc === null) {
		            var onClickButtonHtml ="<input type='button' class='btn2 pbtn_60' onmouseout=\"this.style.borderColor='#dcdcdc'\" onmouseover=\"this.style.borderColor='#f76b00'\" value='删除' style=\"border-color: rgb(220, 220, 220);\"  onclick=\"onClickDelete_Step2('" + iid + "')\">"
		            var result = "<div id='" + iid + "' class='piids_promot'><img src='" + ret.pic_url + "'><br/>" + onClickButtonHtml + "</div>";
		            $("#promot_resp").append(result);
          		}
        	}
      	} else {
        	for (i = 0; i < ids.length; i++) {
          		var ret = jQuery("#promot_gridTable").jqGrid("getRowData", ids[i]);
          		$("#piid" + ret.iid).remove();
        	}
      }
    },
    jsonReader: {
      root: "dataset",
      page: "pager.curPageNo",
      total: "pager.totalPages",
      records: "pager.totalCount",
      repeatitems: false
    },
    prmNames: {
      rows: "pager.pageSize",
      page: "pager.curPageNo",
      sort: "pager.orderBy",
      order: "pager.order"
    },
    pager: "#promot_gridPager"
  });
}

$(function () {
	$("#custom").click(function () {
    	$("#seller_cats_promote_div").hide();
    	$("input[name=seller_cats_promote]:checked").each(function(){
			$(this).attr('checked','');
    	}); 
    	$("#promot_grid").show(); // 显示自定义选择用的grid
  	});
  
	$("#someCategory").click(function () {
	    $("#seller_cats_promote_div").show();
	    $("#promot_grid").hide();
	    $(".piids_promot").remove(); // 删除自定义方式选择的宝贝
	    $("#promot_gridTable").jqGrid("resetSelection");
  	});
  
	$("input[id*='uncustomed']").click(function () { // 当选择非自定义【所有宝贝、所有上架宝贝、所有仓库中的宝贝】时
	    $("#promot_grid").hide(); // 隐藏自定义选择用的grid
	    $(".piids_promot").remove(); // 删除自定义方式选择的宝贝
	    $("#promot_gridTable").jqGrid("resetSelection");
	    $("#seller_cats_promote_div").hide();
	    $("input[name=seller_cats_promote]:checked").each(function(){
	    	$(this).attr('checked','');
	    });  
  	});
});

function doRefresh2() {
  jQuery("#promot_gridTable").jqGrid("setGridParam", {
    url: "items.action?refresh=true",
    page: 1
  }).trigger("reloadGrid");
}


function setPromotGridTableSelection() {
	var rownum = $("#promot_gridTable").jqGrid("getGridParam", "rowNum");
  	if(rownum===undefined || rownum==null) return;
  	
  	$("#promot_gridTable").jqGrid("resetSelection");
  	$(".piids_promot").each(function () {
    	var iid = $(this).attr("id");
    	for (i = 1; i <= rownum; i++) {
      		var ret = $("#promot_gridTable").jqGrid("getRowData", i);
      		if ("piid" + ret.iid == iid) {
        		$("#promot_gridTable").setSelection(i);
      		}
    	}
  	});
}

function onClickDelete_Step2(id) {
	$("#" + id).remove();
  	setPromotGridTableSelection();
}

function doSearch2() {
	var searchKey = jQuery("#promot_searchKey").val();
  	searchKey = encodeURI(encodeURI(searchKey));
  	jQuery("#promot_gridTable").jqGrid("setGridParam", {
    	url: "items.action?cid=" + $('#seller_cats_2').val()+"&approveStatus="+$("#approve_status_2").val()+"&searchKey="+searchKey,
    	page: 1
  	}).trigger("reloadGrid");
}

function validate_tab() {
	var promot = $("input[name='promot']:checked").val();
	switch(promot) {
		case "custom" :
			var piids = buildItemIidStr("piids_promot");
			if(empty(piids)) {
				alert("您尚未选择要卸载推广模块的宝贝！！！");
				return false;
			}
			return true;
		case "someCategory" : 
			var cats = getCheckboxValues("seller_cats_promote");
			if(empty(cats)) {
				alert("您尚未选择要卸载推广模块的类目！！！");
				return false;
			}
			return true;
		case "all" : case "onSale" : default :
			return true;
	}
}

function uninstall() {
	var installPlaces = getCheckboxValues("install_place_checkbox");
	if(empty(installPlaces)) {
		alert("您尚未选择安装位置！！！");
		return;
	}
	
	var params = {"installPlaces":installPlaces};
	params["promot"] = $("input[name='promot']:checked").val();
	switch(params["promot"]) {
		case "custom" : 
			params["installItemIids"] = buildItemIidStr("piids_promot");break;
		case "someCategory" : 
			params["cats"] = getCheckboxValues("seller_cats_promote");
			break;
		case "itemCategory" : 
			params["cats"] = getCheckboxValues("item_cats_promote");
			break;
		case "all" : case "onSale" : default : 
			break;
	}
	
	var wait_html = "<div style='margin-left: 80px; font-size: 12px; display: none;' id='waiting'>";
	wait_html += "<img style='margin-left: 250px;' src='/img/waiting.gif'>";
	wait_html += "<br>根据您安装代码的宝贝数量及网络情况，这可能需要1-15分钟，请耐心等待，不要关闭页面。</div>";
	$('#submit_feedback_div').html(wait_html);
	$('#submit_feedback_div').show();

	$.post("uninstall.action",  params,
    	function(data,status) {
    		$('#submit_feedback_div').html(data.result);
    	}, 
    	"json"
    );
}
